<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部-->
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click.native="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="excel">导出</el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPerm('addEmployee')"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="180" prop="username">
            <template slot-scope="scope">
              <img v-imgerror="require('@/assets/common/head.jpg')" :src="scope.row.staffPhoto" class="headerimg" @click="showCode(scope.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployes(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="pageSetting.total"
            :page-size="pageSetting.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹窗 -->
      <addDialog :show-dialog.sync="showDialog" @refresh="refresh" />
      <!-- 二维码弹窗 -->
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
        <div class="code">
          <canvas ref="myCanvas" />
          <img :src="avatarUrl" alt="" class="codeimg">
        </div>

      </el-dialog>
      <!-- 角色弹窗 -->
      <assignRole
        ref="assignRole"
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getdetailEmployee } from '@/api/employeeSimple'
import employeesHireType from '@/api/constant/employees'
import { formatDate } from '@/filters'
import { delEmployes } from '@/api/employeeSimple'
// 引入弹窗组件
import addDialog from '@/views/employees/components'
// 角色弹窗
import assignRole from './components/assign-role'
// 生成二维码组件
import QRCode from 'qrcode'
export default {
  components: {
    addDialog, assignRole
  },
  data() {
    return {
      loading: false,
      list: [],
      pageSetting: {
        page: 1,
        size: 2,
        total: 0
      },
      showDialog: false,
      isShowCode: false, // 二维码弹窗
      avatarUrl: '',
      // 处理角色分配功能
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getdetailEmployee()
  },
  methods: {
    // 刷新数据 从新加载
    refresh() {
      this.getdetailEmployee()
    },

    // 获取员工详情数据
    async getdetailEmployee() {
      // 加载状态
      this.loading = true
      const { total, rows } = await getdetailEmployee(this.pageSetting)
      this.list = rows
      this.pageSetting.total = total
      // 加载完成
      this.loading = false
      console.log(rows)
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getdetailEmployee()
    },
    formatEmployment(row, column, cellValue) {
      // 这里可以接受到当前格子的数据
      // 一共四个参数
      // 在这里可灵活的进行格式化,
      // 最终 return 的值会显示在页面上
      // 从枚举数据中找到 id 跟我的格子数据一样的对象, 输出他的 value 即可
      const obj = employeesHireType.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 点击导出 按需引入导出插件的方法
    async excel() {
      const excel = await import('@/vendor/Export2Excel')
      // 导出的方法 导出 json 数据
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     ['tom', 666, '男'],
      //     ['rose', 666, '女']
      //   ]
      // })

      // 从后台拿去到所有员工的数据
      const { rows } = await getdetailEmployee({
        page: 1,
        size: this.pageSetting.total
      })
      // console.log(rows)
      // 字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      // console.log(header)
      // 准备data 二维数组
      const data = rows.map(user => {
        return this.obj2Array(user, dict)
      })
      // console.log(data)
      // 调用方法 导出
      excel.export_json_to_excel({
        header,
        data
      })
    },
    // 对象转为数组的函数
    obj2Array(user, dict) {
      const newArry = []
      // 遍历dict 拿到字典中的对应英文字符 按照英文字符找到对应的值
      for (const key in dict) {
        const enKey = dict[key]
        let value
        // 判断 如果 遍历到的是时间 进行处理
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 通过在字典里面找到的对应key 在user下找到对应的值
          value = formatDate(user[enKey])
        } else if (enKey === 'formOfEmployment') {
          // 如果是状态
          const obj = employeesHireType.hireType.find(item => item.id === user[enKey])
          value = obj ? obj.value : '未知形式'
        } else {
          value = user[enKey]
        }
        // console.log(enKey)
        // console.log(value)
        newArry.push(value)
      }
      // console.log(newArry)
      return newArry
    },
    // 点击删除员工
    async delEmployes(id) {
      // 提示是否删除
      await this.$confirm('是否删除')
      await delEmployes(id)
      // 提示删除成功
      this.$message.success('操作成功')
      // 重新加载页面
      this.getdetailEmployee()
    },
    showCode(url) {
      // 判断是否有图片地址 如果有 就显示弹窗
      if (url) {
        this.isShowCode = true
        // 在二维码上添加头像
        this.avatarUrl = url
        // 生成二维码
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    async assignRole(id) {
      // 1. 通知子组件获取这个员工的已有角色进行渲染
      await this.$refs.assignRole.getUserDetailById(id)
      // 2. 弹出弹窗
      this.showRoleDialog = true
      // 3. 将当前的点击 id 记录下来供后续使用
      this.userId = id
    }
  }
}
</script>

<style lang='scss' scoped>
.headerimg{
  width: 100%;
}
.code{
  display: flex;
  justify-content: center;
  align-items: center;
}
.codeimg{
  position: absolute;
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 50%;
}
</style>
